<template>
  <div id="app">
    <div class='login_bt'>
      <p>友情提示: 因为facebook api一段时间内访问有流量限制, 小伙伴工作时间尽量错开哈~ 使用时可以在群通报一声.</p>
      <el-button type="primary"
                 :loading="loading"
                 @click='resetLogin'>如果访问令牌失效了,才点击重新登录</el-button>
      <el-button type="primary"
                 :loading="adLoading"
                 @click='getNewAdaccounts'>如果广告账户有新添,才点击重新获取广告账户</el-button>
    </div>
    <el-tabs :tab-position="tabPosition">
      <el-tab-pane label="导出列表">
        <ads></ads>
      </el-tab-pane>
      <!-- <el-tab-pane label="配置管理"></el-tab-pane> -->
    </el-tabs>
  </div>
</template>

<script>
import Vue from 'vue'
import api from './utils/fb_http.js'
import Ads from 'components/ads.vue'
import { getAdaccounts } from 'utils/api.js'

export default {
  name: 'app',
  components: {
    Ads
  },
  data: function () {
    return {
      isFBReady: false,
      access_token: '',
      tabPosition: 'left',
      loading: false,
      adLoading: false,
      mark: true
    }
  },
  mounted: function () {
    this.isFBReady = Vue.FB != undefined
    window.addEventListener('fb-sdk-ready', this.onFBReady)
  },
  beforeDestroy: function () {
    window.removeEventListener('fb-sdk-ready', this.onFBReady)
  },
  methods: {

    async onFBReady () {
      this.isFBReady = true
      this.login()
    },
    resetLogin () {
      this.loading = true
      this.$store.dispatch('clearData')
      this.login()
    },
    login () {
      if (!this.isFBReady) return false
      let that = this
      let { access_token, user_id, options } = this.$store.state
      if (!access_token && !user_id) {
        Vue.FB.login(async function (response) {
          let { accessToken, userID } = response.authResponse
          that.$store.commit('setToken', accessToken)
          // 如果不同账户 重新存储 user_id options
          if (userID !== user_id || options.length === 0) {
            that.$store.commit('setUserId', userID)
            let new_options = await getAdaccounts()
            if (options.length !== new_options.length) that.$store.commit('setOptions', new_options)
          }
          that.loading = false
        });
      } else {
        that.loading = false
      }

    },
    // 重新获取广告账户
    async getNewAdaccounts () {
      if (!this.mark) return false
      this.mark = false
      this.adLoading = true
      let new_options = await getAdaccounts()
      this.$store.commit('setOptions', new_options)

      this.mark = true
      this.adLoading = false
    }
  }
}
</script>

<style lang='stylus'  rel='stylesheet/stylus'>
#app
  font-family 'Avenir', Helvetica, Arial, sans-serif
  -webkit-font-smoothing antialiased
  -moz-osx-font-smoothing grayscale
  text-align center
  color #2c3e50
  min-width 1000px
.login_bt
  // text-align cen
.el-tabs
  margin-top 60px
.el-tabs__content
  width 900px
</style>